<?php
/*
 * @美潮风
 * @功能说明：明星机构模块
 * @更新说明：暂无更新
 * @文件名 HospitalController.class.php
 * @编码 UTF-8
 * @创建时间 2016-9-18 下午16:21:25
 * @创建人 yanyan
 */
namespace home\Controller;

use Think\Controller;
class HospitalController extends ApibaseController
{

    /**
     * 分医院科室管理
     * @date: 2017-10-26 下午17:30:20
     * @editor: yanyan
     */
    public function depart(){
        $page = I('get.page') ?: 1;
        $perpage = 10;
        $list = M('Department');
        $url = $output = $outtype = array();
        if(I('get.de_name')){
            $list = $list->where('de_name LIKE "%'.I('get.de_name').'%"');
            $url['de_name'] = I('get.de_name');
        }
        if(I('get.de_mobile')){
            $list = $list->where(array('de_mobile'=>I('get.de_mobile')));
            $url['de_mobile'] = I('get.de_mobile');
        }
        $custObject = clone $list;

        $departData = $list->page($page, $perpage)->select();
        foreach ($departData as $key => $value) {
            if($value['parent_id'] > 0){
                $parent = M('Department')->where(['id'=>$value['parent_id']])->find();
                $departData[$key]['de_name'] = '|__'.$value['de_name'];
                $departData[$key]['parent_name'] = $parent['de_name'];
            }
        }
        $this->assign('departData',$departData);
        $this->assign('page', setPage($custObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('hospital/depart');
    }

    /**
     * 铜人宝_一级科室接口
     * @date: 2017-10-26 下午17:30:20
     * @editor: yanyan
     */
    public function parentData(){
        $data = M('Department')->where(['parent_id'=>0])->select();
        if($data){
            dataFormat($data,0,'');
        }else{
            dataFormat('',1,'暂无数据');
        }
    }

    /**
     * 铜人宝_二级科室接口
     * @date: 2017-10-26 下午17:30:20
     * @editor: yanyan
     */
    public function childData(){
        $data = M('Department')->where(['parent_id'=>['neq',0]])->select();
        if($data){
            dataFormat($data,0,'');
        }else{
            dataFormat('',1,'暂无数据');
        }
    }

    /**
     * 铜人宝_添加医院科室
     * @date: 2017-10-26 下午17:30:20
     * @editor: yanyan
     */
    public function addDepart() {
        //科室名称和级别为必填项
        if(I('post.de_name')){
            if(I('post.id')){
                $effectId = M('Department')->where(array('id'=>I('post.id')))
                    ->setField(array(
                        'de_name' => I('post.de_name'),
                        'de_mobile' => I('post.de_mobile'),
                        'parent_id' => I('post.parent_id')?:0,
                        'sort' => I('post.sort')?:0,
                        'status' => 1,
                        'update_at' => time()
                    ));
                if($effectId){
                    dataFormat('',0,'科室更新成功');
                }else{
                    dataFormat('',1,'操作失败');
                }
            }
             //已存在的科室名不能再次添加
            $depart = M('Department')->where(['de_name'=>I('post.de_name')])->find();
            if($depart){
                dataFormat('',1,'该科室已存在');
            }
            $data = array(
                'de_name' => I('post.de_name'),
                'de_mobile' => I('post.de_mobile'),
                'parent_id' => I('post.parent_id')?:0,
                'sort' => I('post.sort')?I('post.sort'):0,
                'status' => 1,
                'add_at' => time(),
                'update_at' => time()
            );
            if(M('Department')->add($data)){
                dataFormat('',0,'科室添加成功');
            }else{
                dataFormat('',1,'添加失败');
            }
        }else{
            dataFormat('',1,'参数缺失');
        }
    }

    /*
     * 铜人宝_医院科室删除
     *  @date: 2016-9-19 下午17:50:20
     * @editor: yanyan
     */
    public function deleteDepart() {
        if (I('post.de_id')) {
            //判断是否为一级科室（需要删除对应的子科室）
            $depart = M('Department')->where(array('id' => I('post.de_id')))->find();
            $rs = M('Department')->where(array('id' => I('post.de_id')))->delete();
            if($depart['parent_id'] == 0){
                M('Department')->where(array('parent_id' => I('post.de_id')))->delete();
            }
            if($rs){
                dataFormat('',0,'医院科室删除成功');
            }else{
                dataFormat('',1,'科室删除失败');
            }
        }else{
            dataFormat('',1,'参数缺失');
        }
    }

    /**
     * 铜人宝_分医院人员列表
     * @date: 2017-10-30 下午14:30:20
     * @editor: yanyan
    */
    public function hos_user(){
        $page = I('get.page') ?: 1;
        $perpage = 20;
        $list = M('UserInfo');
        $depart = M('Department');
        $url = $output = $outtype = array();
        if(I('get.user_name')){
            $list = $list->where('user_name LIKE "%'.I('get.user_name').'%"');
            $url['user_name'] = I('get.user_name');
        }
        if(I('get.mobile')){
            $list = $list->where(array('mobile'=>I('get.mobile')));
            $url['mobile'] = I('get.mobile');
        }
        if(I('get.depart_id')){
            $list = $list->where(array('depart_id'=>I('get.depart_id')));
            $url['depart_id'] = I('get.depart_id');
        }
        $custObject = clone $list;

        $userData = $list->order('user_id desc')->page($page, $perpage)->select();
        if ($userData){
            foreach ($userData as $key=>$val){
                $departData = $depart->where(['id'=>$val['depart_id']])->find();
                $userData[$key]['de_name'] = $departData['de_name'];
                //上级主管
                if($departData['parent_id'] > 0){
                    $userData[$key]['last_leader'] = $depart->where(['id'=>$departData['parent_id']])->getField('de_leader');
                }
            }
        }
        //科室列表
        $department = M('Department')->where(['parent_id'=>['neq',0]])->select();
        $this->assign('userData',$userData);
        $this->assign('depart',$department);
        $this->assign('page', setPage($custObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('hospital/hos_user');
    }

    /**
     * 铜人宝_添加医院人员
     * @date: 2017-10-31 下午15:30:20
     * @editor: yanyan
     */
    public function add_user() {
        if (I('post.postData')) {
            parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
        }
        //user_type 1领导 2科室 3后勤
        if($postData['user_type'] && $postData['user_type_name'] && $postData['user_name'] && $postData['password'] && $postData['mobile']){

            if(I('post.id')){
                $effectId = M('UserInfo')->where(array('id'=>I('post.id')))
                    ->setField(array(
                        'user_name' => $postData['user_name'],
                        'mobile' => $postData['mobile'],
                        'user_type' => $postData['user_type'],
                        'age' => $postData['age'],
                        'sex' => $postData['sex'],
                        'head_img' => uploadQiniu(UPLOAD_PATH . $postData['head_img'], 'head'),
//                        'head_img' => uploadQiniu(UPLOAD_PATH . $postData['head_img'], 'head'),
                        'job' => trim($postData['job']),
                        'depart_id' => $postData['depart_id']?:0,
                        'status' => 1,
                        'update_at' => time()
                    ));
                if($effectId){
                    dataFormat('',0,'用户更新成功');
                }else{
                    dataFormat('',1,'操作失败');
                }
            }
            $salt = randstr(5);
            $password = md5($postData['password'] . $salt);
            //生成唯一标识的规则
            $data = array(
                'user_name' => $postData['user_name'],
                'mobile' => $postData['mobile'],
                'user_type' => $postData['user_type'],
                'age' => $postData['age'],
                'sex' => $postData['sex'],
                'user_type_name' => $postData['user_type_name'],
                'salt' => trim($salt),
                'password' => trim($password),
                'head_img' => uploadQiniu(UPLOAD_PATH . $postData['head_img'], 'head'),
                'job' => trim($postData['job']),
                'depart_id' => $postData['depart_id']?:0,
                'status' => 1,
                'good_at' => $postData['good_at'],
                'add_at' => time(),
                'update_at' => time()
            );
            if(M('UserInfo')->add($data)){
                dataFormat('',0,'用户添加成功');
            }else{
                dataFormat('',1,'操作失败');
            }
        }else{
            dataFormat('',1,'参数缺失');
        }

    }

    public function upFile()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     0 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     $_SERVER['DOCUMENT_ROOT'] . '/statics/upload/head_img/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            exit(json_encode(['code'=>1,'msg'=>'上传失败']));
        }else{
            exit(json_encode(['code'=>0,'msg'=>'/statics/upload/head_img/'.$info['file']['savepath'].$info['file']['savename']]));
        }
    }

    /**
     * 根据地理位置获取经纬度
     * param  addr
     * @return json
     * author liuqi
     */
    public function getLal(){
        $addr = I('post.addr');
        $return = file_get_contents('http://api.map.baidu.com/geocoder/v2/?address='.$addr.'&output=json&ak=d7IG6wfuKy6EkfAvka9rm1GGztEE4GBO');
        $return = json_decode($return,true);
        if($return['status'] == 0){
            exit(json_encode(['code'=>$return['status'],'result'=>['lng'=>$return['result']['location']['lng'],'lat'=>$return['result']['location']['lat']]]));
        }else{
            exit(json_encode(['code'=>1,'result'=>'获取失败']));
        }
    }

    /**
     * 设置机构推荐
     */
    public function setRecommend(){
        $id = I('post.id');
        $rec = I('post.rec');
        $HosptEntity = M('HosptEntity');
        if($id){
            if(!$rec){
                $count = $HosptEntity->where(['is_recommend'=>1])->count();
                if($count>=4){
                    dataFormat('',2,'推荐人数已超过四个，无法推荐');
                }
                $result = $HosptEntity->where(['hospt_id'=>$id])->setField(['is_recommend'=>1,'update_at'=>time()]);
                if($result){
                    dataFormat('',0,'推荐成功');
                }else{
                    dataFormat('',3,'推荐失败');
                }
            }else{
                $res = $HosptEntity->where(['hospt_id'=>$id])->setField(['is_recommend'=>0,'update_at'=>time()]);
                if($res){
                    dataFormat('',0,'已取消推荐');
                }else{
                    dataFormat('',4,'操作失败');
                }
            }
        }else{
            dataFormat('',1,'参数错误');
        }
    }

    /**
     * 用户禁用启用(status 1禁用 2启用)
    */
    public function user_status(){
        if(I('post.user_id') && I('post.status')){
            $user_id = I('post.user_id');
            $status = I('post.status')==1 ? 1:0;
            $rs = M('UserInfo')->where(['user_id'=>$user_id])->setField(['status'=>$status]);
            if ($rs){
                dataFormat('',0,'success');
            }
        }else {
            dataFormat('',1,'参数缺失');
        }
    }
}